import collections
class Solution:
	# @param {integer} numCourses
	# @param {integer[][]} prerequisites
	# @return {boolean}
	def findOrder(self, numCourses, prerequisites):
		mention = set()
		graph = dict()
		income = dict()
		for edge in prerequisites:
			if edge[0] in income:
				income[edge[0]] += 1 if (edge[1] not in graph) or (edge[0] not in graph[edge[1]]) else 0
			else:
				income[edge[0]] = 1

			if edge[1] not in income:
				income[edge[1]] = 0

			if edge[1] in graph:
				graph[edge[1]].add(edge[0])
			else:
				graph[edge[1]] = set([edge[0]])

			mention.add(edge[0])
			mention.add(edge[1])
		points_number = len(mention)
		count = 0
		que = collections.deque([k for k in income.iterkeys() if income[k] == 0])
		ans = []
		while que:
			p = que.popleft()
			ans.append(p)
			count += 1
			if p not in graph:
				continue
			for e in graph[p]:
				income[e] -= 1
				if income[e] == 0:
					que.append(e)
		if count == points_number:
			ans.extend(list(set(range(numCourses)) - mention))
			return ans
		else:
			return []

if __name__ == '__main__':
	pre = [[1,0],[2,0],[3,1],[3,2]]
	print Solution().findOrder(7, pre)